package com.wang.admin.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.wang.admin.entity.LoginUser;
import com.wang.admin.entity.SysUser;
import com.wang.admin.service.UserService;
import com.wang.commom.constant.Constants;
import com.wang.commom.constant.UserConstants;
import com.wang.commom.exception.ServiceException;
import com.wang.commom.exception.user.UserNotExistsException;
import com.wang.commom.exception.user.UserPasswordNotMatchException;
import com.wang.commom.security.context.AuthenticationContextHolder;
import com.wang.commom.utils.*;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.BadCredentialsException;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.Authentication;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: tiger
 * @Data: 2024/10/14 23:09
 * @Description: 用户
 **/

@Service
@DS("master")
public class UserServiceImpl implements UserService {

//    @Autowired
//    private AuthenticationManager authenticationManager;

    @Value("${token.secret}")
    private String secret;

    /**
     * @Date: 2024/10/14 23:10
     * @Description: 用户登录
     **/
    @Override
    public String login(String username, String password, String code, String uuid) {

        //验证码校验 TODO
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证 TODO
        //Authentication authentication = null;

        try {
            //UsernamePasswordAuthenticationToken usernamePasswordToken = new UsernamePasswordAuthenticationToken(username, password);
            //AuthenticationContextHolder.setContext(usernamePasswordToken);
            //authentication = authenticationManager.authenticate(usernamePasswordToken);
        } catch (Exception ex) {
//            if (ex instanceof BadCredentialsException) {
//                //TODO
//                throw new UserPasswordNotMatchException();
//            } else {
//                //TODO
//                throw new ServiceException(ex.getMessage());
//            }

        } finally {
            //AuthenticationContextHolder.clearContext();
        }
        //TODO 异步返回
        //LoginUser loginUser = (LoginUser) authentication.getCredentials();

        //recordLoginInfo(loginUser.getUserId());
        // 生成token TODO createToken(loginUser);

        return "";
    }

    /**
     * @return void
     * @Description: TODO - 修改用户基本信息
     * @Date 2024/10/15 12:12
     * @Param [sysUser]
     */
    @Override
    public void updateUserProfile(SysUser sysUser) {

    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);

        return createToken(claims);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息 -TODO
     */
    public void refreshToken(LoginUser loginUser) {

    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        System.out.println("setUserAgent");
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }


    /**
     * @MethodName: loginPreCheck
     * @Param: [username, password]
     * @Return: void
     * @Date: 2024/10/14 23:11
     * @Description: 登录前置校验
     **/
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {

            //TODO 异步返回
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误  --密码长度
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            //TODO 异步返回
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误  -- 用户名长度
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            //TODO 异步返回
            // TODO 有异常
            throw new UserPasswordNotMatchException();
        }

        // IP黑名单校验 TODO


    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        this.updateUserProfile(sysUser);
    }
}
